﻿﻿using System;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace IPScanner
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "正在查询";
            button1.Enabled = false;
            try
            {
                if (!isValidIpAddess(this.IPTextBox.Text))
                {
                    MessageBox.Show("Sorry, IP地址不合法!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                WebClient client = new WebClient();
                string uri = @"http://ip.taobao.com/service/getIpInfo.php?ip=" + this.IPTextBox.Text;
                string jsonData = client.DownloadString(uri);
                IPCheckResult result = JsonConvert.DeserializeObject<IPCheckResult>(jsonData);
                if (result.code != 0)
                {
                    MessageBox.Show("Sorry, nothing found！");
                    return;
                }
                this.countryTextBox.Text = result.data.country;
                this.areaTextBox.Text = result.data.area;
                this.regiontextBox.Text = result.data.region;
                this.cityTextBox.Text = result.data.city;
                this.ISPTextBox.Text = result.data.isp;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "发现异常");
            }
            finally
            {
                button1.Enabled = true;
                button1.Text = "查询";
            }
        }

        private bool isValidIpAddess(string ip)
        {
            string pattern = @"^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))$";

            return Regex.IsMatch(ip, pattern);
        }
    }
}